package muilty_thread.java_current_practice_and_kernel.cp5;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

public class ServiceManager {
    static Set<Service> set = new HashSet<>();
    static volatile CountDownLatch latch;

    static {
        latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            set.add(new Service("sb" + new Random(), latch));
        }
    }
    public static void startServices(){
        for (Service service : set) {
            service.start();
        }
    }

    public static boolean checkServiceStatus(){
        boolean allIsOk = true;
        try {
            latch.await();
        } catch (InterruptedException e) {
            return false;
        }
        for (Service service : set) {
            if (!service.isStarted()) {
                allIsOk = false;
                break;
            }
        }
        return allIsOk;
    }

}
class Service{
    private boolean started = false;
    private String name;
    final CountDownLatch latch;

    public Service(CountDownLatch latch) {
        this.latch = latch;
    }

    public Service(String name, CountDownLatch latch) {
        this.name = name;
        this.latch = latch;
    }

    public void start() {
        new ServiceStarter().start();
    }

    public boolean isStarted(){
        return  started;
    }
    class ServiceStarter extends Thread{
        @Override
        public void run(){
            try {
                started = true;
            }finally {
                latch.countDown();
            }
        }
    }

}